package com.ohuang.jiaxiaotong.Activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bunny.android.library.LoadDataLayout;
import com.example.myhttp.CallBackString;
import com.example.myhttp.Ihttp;
import com.ohuang.jiaxiaotong.MyHttpURL;
import com.ohuang.jiaxiaotong.R;
import com.ohuang.jiaxiaotong.Util.EventMsgCode;
import com.ohuang.jiaxiaotong.Util.Ohuang;
import com.ohuang.jiaxiaotong.base.BaseAc;
import com.ohuang.jiaxiaotong.entity.ClassMember;
import com.ohuang.jiaxiaotong.entity.EventMsg;
import com.ohuang.jiaxiaotong.entity.User;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;

//班级成员信息
public class ClassInfoActivity extends BaseAc {
    private ListView listView;
    private ArrayList<ClassMember> mData;
    private CommonAdapter commonAdapter;
    private Button button_exit;
    private User user;
    private LoadDataLayout loadDataLayout;
    private String className;
    private Dialog dialog;
    private static final int RE_SUCCESS = 0, RE_FAIL = 1, RE_ERROR = 2, RE_OTHER = 3;
    private Dialog dialogLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_class_info);
        setTitle("班级成员");
        Intent intent = getIntent();
        className = intent.getStringExtra("className");
        EventBus.getDefault().register(this);
        Ohuang.changeStatusBarTextImgColor(this, true);
        Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(R.mipmap.icon_goback);//设置ActionBar返回按钮
        button_exit = findViewById(R.id.btn_exitClass_classInfo);
        listView = findViewById(R.id.listView_classInfo);
        loadDataLayout = findViewById(R.id.loadData_classInfo);
        initView();
    }

    private void initView() {
        //退出班级按钮
        button_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog = Ohuang.reconfirmDialogShow(ClassInfoActivity.this, "退出班级", "你确定要退出班级吗？"
                        , V -> {
                    dialogLoading=Ohuang.dialogLoadingshow(ClassInfoActivity.this,"正在退出班级");
                            httpExitClass();
                            dialog.dismiss();
                        });
            }
        });
        loadDataLayout.showLoading("正在努力加载中", new LoadDataLayout.SetImgCallBack() {
            @Override
            public void setImg(ImageView img) {
                Glide.with(ClassInfoActivity.this)
                        .load(R.drawable.gif_loading)
                        .into(img);
            }
        });//显示 load布局 状态正在加载
        httpGetClassMember();
    }

    //执行退出登录操作
    private void httpExitClass() {
        HashMap<String,String>  map=new HashMap<>();
        map.put("username", user.getUsername());
        map.put("className", className);
        Ihttp.getInstance().post(MyHttpURL.mainUrl + "user/quitClass", map, new CallBackString() {
            @Override
            public void success(String ojb) {
                String code = ojb;
                if ("success".equals(code)) {
                    myHandler.sendEmptyMessage(RE_SUCCESS);
                } else {
                    myHandler.sendEmptyMessage(RE_OTHER);
                }
            }



            @Override
            public void fail(String s) {
                myHandler.sendEmptyMessage(RE_ERROR);
            }
        });


    }

    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case RE_SUCCESS:
                    EventBus.getDefault().post(new EventMsg(EventMsgCode.CODE_1,""));
                    dialogLoading.dismiss();
                    Ohuang.dialogshow(ClassInfoActivity.this, "退出成功", "你已成功退出班级。", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    break;
                default:
                    dialogLoading.dismiss();
                    Toast.makeText(ClassInfoActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    //获取班级成员
    private void httpGetClassMember() {
//创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyHttpURL.mainUrl + "user/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GithubService service = retrofit.create(GithubService.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("className", className);
        service.getClassMember(map).enqueue(new Callback<ArrayList<ClassMember>>() {
            @Override
            public void onResponse(Call<ArrayList<ClassMember>> call, Response<ArrayList<ClassMember>> response) {
                loadDataLayout.showSuccess();
                mData = response.body();
                commonAdapter = new CommonAdapter(ClassInfoActivity.this, R.layout.list_classinfo_item, mData) {
                    @Override
                    protected void convert(ViewHolder viewHolder, Object item, int position) {
                        if ("0".equals(((ClassMember) item).getRole())) {
                            viewHolder.setText(R.id.txt_classInfo_list, "老师：" + ((ClassMember) item).getUsername());
                            if (user != null) {
                                if ((user.getUsername()).equals(((ClassMember) item).getUsername())) {
                                    viewHolder.setText(R.id.txt_classInfo_list, "老师：" + ((ClassMember) item).getUsername() + "(我)");
                                }
                            }

                        } else {
                            viewHolder.setText(R.id.txt_classInfo_list, "家长：" + ((ClassMember) item).getUsername());
                            if (user != null) {
                                if ((user.getUsername()).equals(((ClassMember) item).getUsername())) {
                                    viewHolder.setText(R.id.txt_classInfo_list, "家长：" + ((ClassMember) item).getUsername() + "(我)");
                                }
                            }
                        }
                        ImageView imageView = viewHolder.getView(R.id.img_classInfo_list);
                        Glide.with(ClassInfoActivity.this).load(((ClassMember) item).getIconUrl())
                                .error(R.drawable.img_icon)
                                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                .into(imageView);
                    }
                };

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(ClassInfoActivity.this, UserMsgActivity.class);
                        intent.putExtra("username", mData.get(position).getUsername());
                        intent.putExtra("role", mData.get(position).getRole());
                        intent.putExtra("iconUrl", mData.get(position).getIconUrl());
                        startActivity(intent);
                    }
                });

                listView.setAdapter(commonAdapter);
            }

            @Override
            public void onFailure(Call<ArrayList<ClassMember>> call, Throwable t) {
                loadDataLayout.showError();
            }
        });
    }

    interface GithubService {
        //https://api.github.com/repos/{owner}/{repo}/contributors
        @POST("findAllUser")
        Call<ArrayList<ClassMember>> getClassMember(@QueryMap HashMap<String, String> deviceInfo);
    }


    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (item.getItemId() == android.R.id.home) {//左上角返回按钮
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void GetUserEventBus(User user) {
        this.user = user;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
